<!--
  ~ Copyright (c) 2005, 2014 vacoor
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title></title>
</head>
<body>
<div id="encoder">
    <input id="source" name="source" type="text">
    Result: <span id="result"></span>
    <hr>
    <button id="encode">encode(To PPPoE)</button>
    <br>
    <button id="decode">decode(To Telephone)</button>
</div>
<script type="text/javascript">
    function encode(source) {
        var result = '';
        var dic = '9012345678abcdeABCDEFGHIJKLMNfghijklmnUVWXYZxyzuvwopqrstOPQRST';
        var mask = [17, 52, 201, 35, 117, 24, 215, 226, 18, 53, 41, 43, 236, 182, 35, 25];
        var cache = 37;

        var l = 0;
        for (var i = 0; i < source.length; i++) {
            for (var j = 0; j < dic.length; j++) {
                if (source[i] == dic[j]) {
                    l = (((mask[i & 0xF]) ^ (3 * cache)) ^ (i * 5)) + j;
                    result += dic[l % dic.length];
                    cache ^= l % dic.length + 9433;
                    break;
                }
            }
            if (result[i] == '') {
                dic[i] = i;
            }
        }
        return '2:' + result;
    }

    function decode(source) {
        var dics = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var result = '';
        for (var j = 0; j < source.length; j++) {
            for (var i = 0; i < dics.length; i++) {
                var tmp = result + dics[i];
                if (source.substring(0, j + 1) == encode(tmp)) {
                    result = tmp;
                    break;
                }
            }
        }
        return result;
    }
    /***********************/
    document.getElementById("encode").onclick = function () {
        document.getElementById("result").innerHTML = encode(document.getElementById("source").value.trim());
    }

    document.getElementById("decode").onclick = function () {
        document.getElementById("result").innerHTML = decode(document.getElementById("source").value.trim());
    }
</script>
</body>
</html>
